package service

import (
	"context"
	"github.com/spf13/cast"
	"log"
	"nearby/biz/common"
	"nearby/biz/domain/entity"
	"nearby/biz/domain/service"
	"nearby/biz/model"
)

type GetMomentDetailService struct {
}

func (ss *GetMomentDetailService) Execute(ctx context.Context, req *model.GetMomentDetailRequest) (*model.GetMomentDetailResponse, error) {
	momentEntity, err := entity.GetMomentEntity(ctx, entity.GetMomentEntityRequest{
		MomentID: cast.ToInt64(req.MomentID),
	})
	if err != nil {
		log.Printf("entity.GetMomentEntity fail, err: %+v", err)
		return nil, common.NewBizErr(common.BizErrCode, "ops, 没有找到该动态...", err)
	}
	err = ss.LoadMomentInfo(ctx, momentEntity)
	if err != nil {
		log.Printf("加载用户信息失败, err: %+v", err)
	}
	{
		// 浏览量较小时, 直接同步浏览量
		ctxCopy, cancel := context.WithCancel(ctx)
		go func() {
			if momentEntity.ViewCount < 1000 {
				var viewService ViewMomentDetailService
				err = viewService.SyncViewCnt(ctxCopy, cast.ToInt64(req.MomentID), 1)
				if err != nil {
					log.Printf("同步浏览量失败")
				}
			}
			cancel()
		}()
	}
	return &model.GetMomentDetailResponse{
		Meta:   common.MetaOk,
		Moment: momentEntity.ToVo(),
	}, nil
}

func (ss *GetMomentDetailService) LoadMomentInfo(ctx context.Context, momentEntity *entity.Moment) error {
	userDomainService := service.UserService{}
	userEntity, err := userDomainService.GetUserEntityByUserID(ctx, momentEntity.User.UserID)
	if err != nil {
		return err
	}
	momentEntity.User.Nickname = userEntity.Nickname
	momentEntity.User.HeadURL = userEntity.HeadURL
	return nil
}
